<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-28 10:49:51
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, unref, watch } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import SCADAApi from '@/api/scada'
import { Dialog } from '@/components/Dialog'
import { Form } from '@/components/Form'
import { DetectorFormschema, MeasureSchemas, DetecterRules } from './MarkerSchema'
import { useForm } from '@/hooks/web/useForm'
import { BaseButton } from '@/components/Button'
import { useDictStore } from '@/store/modules/dictData'
import MeasureFactors from './MeasureFactors.vue'
import { useTable } from '@/hooks/web/useTable'
import { useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRoute, useRouter } from 'vue-router'
const { go, push } = useRouter()
import { useSCADAStore } from '@/store/modules/scada'
const DictStore = useDictStore()
const scadaStore = useSCADAStore()
DictStore.setDict('scada_ffect_field') //量测标识
DictStore.setDict('scada_meas_unit') //量测标识
const { t } = useI18n()
const ids = ref('')
const currentRow = ref()
const DetectorUuid = ref<any>(useRoute().query.detector)
const deviceNo = ref<any>(useRoute().query.deviceNo)
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await SCADAApi.Getdetectoretail(unref(DetectorUuid))
    currentRow.value = res
    if (res.devType == 0) {
      DetectorFormschema[8].hidden = false
    } else {
      DetectorFormschema[8].hidden = true
    }
    return {
      list: res.measureFactors
    }
  },
  fetchDelApi: async () => {
    const res = await SCADAApi.DeleteMeasureFactor(unref(ids)[0])
    return !!res
  }
})
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref<any>() //树结构ID
const departmentList = ref<any>([]) //树结构数据
const { loading, dataList } = tableState
const { getElTableExpose, delList, getList } = tableMethods
const delLoading = ref(false)
const fetchDepartment = async () => {
  const res = await scadaStore.getMarkerList
  if (res.length == 0) {
    go(-1)
  }
  currentNodeKey.value = unref(deviceNo)
  departmentList.value = res
  unref(treeEl)?.setCurrentKey(currentNodeKey.value) //应用到树结构
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)
const currentChange = (data: any) => {
  //树结构点击
  currentNodeKey.value = data.deviceNo
  push({
    path: '/SCADA/SetMarker',
    query: { deviceNo: data.deviceNo }
  })
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.siteName.includes(value) || data.deviceNo.includes(value)
}
//删除附加设备
const delData = async (row: any | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.uuid] : elTableExpose?.getSelectionRows().map((v: any) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
    getList()
  })
}
//附加设备列表表格结构
const ActionSchemas = [
  {
    field: 'action',
    label: t('tableDemo.action'),
    fixed: 'right',
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    slots: {
      default: (data: any) => {
        return (
          <>
            <span class="TableBtn" onClick={() => MeasureAction(data.row, 'edit')}>
              {t('修改')}
            </span>
            <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
              {t('删除')}
            </span>
          </>
        )
      }
    }
  }
]
const crudSchemas = [...MeasureSchemas, ...ActionSchemas]
const { allSchemas } = useCrudSchemas(crudSchemas)

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
watch(
  () => currentRow.value,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
const dialogVisible = ref(false)
const saveLoading = ref(false)
const DetectorAction = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const i = await SCADAApi.EditDetector(formData)
    if (i) {
      ElMessage.success('修改附加设备成功')
    } else {
      ElMessage.error('修改附加设备失败')
    }
  }
}
const MeasureData = ref()
const actionType = ref('')
const MeasureAction = (row, type: string) => {
  dialogVisible.value = true
  actionType.value = type
  if (type == 'add') {
    MeasureData.value = {
      deteUuid: currentRow.value.uuid,
      devNo: currentRow.value.devNo
    }
  } else {
    MeasureData.value = row
  }
}
const writeRef = ref<ComponentRef<typeof MeasureFactors>>()

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    console.log(formData)
    if (actionType.value == 'add') {
      const res = await SCADAApi.AddMeasureFactor(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
      if (res) {
        dialogVisible.value = false
        ElMessage.success('添加量测成功')
        getList()
      } else {
        ElMessage.error('添加量测失败')
      }
    } else {
      const res = await SCADAApi.EditMeasureFactor(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
      if (res) {
        dialogVisible.value = false
        ElMessage.success('修改量测成功')
        getList()
      } else {
        ElMessage.error('修改量测失败')
      }
    }
  }
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]">
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('搜索站点名称/编号')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        :expand-on-click-node="false"
        node-key="deviceNo"
        :current-node-key="currentNodeKey"
        :highlight-current="true"
        :props="{
          label: 'siteName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.siteName" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.siteName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <div class="flex-[3] ml-20px">
      <ContentWrap class="flex-[3] relative" id="detector" title="附加设备详情">
        <div class="absolute right-[30px] top-[10px]">
          <BaseButton size="small" type="primary" @click="DetectorAction" class="AddbtnStyle">
            <Icon class="mr-[5px]" icon="ep:edit" :size="12" />修改
          </BaseButton>
        </div>
        <div class="absolute left-[15px] top-[10px]">
          <BaseButton size="small" type="primary" @click="go(-1)" class="AddbtnStyle">
            <Icon class="mr-[5px]" icon="ep:back" :size="12" />返回
          </BaseButton>
        </div>
        <Form
          labelPosition="top"
          :rules="DetecterRules"
          @register="formRegister"
          :schema="DetectorFormschema"
        />
      </ContentWrap>
      <ContentWrap class="flex-[3] relative mt-20px" title="量测列表">
        <div class="absolute right-[30px] top-[10px]">
          <BaseButton
            size="small"
            type="primary"
            @click="MeasureAction({}, 'add')"
            class="AddbtnStyle"
          >
            <Icon class="mr-[5px]" icon="ep:plus" :size="12" />新增
          </BaseButton>
        </div>
        <Table
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          sortable
          @register="tableRegister"
        />
        <Dialog v-model="dialogVisible" title="量测">
          <MeasureFactors
            ref="writeRef"
            :form-schema="allSchemas.formSchema"
            :current-row="MeasureData"
          />
          <template #footer>
            <BaseButton type="primary" :loading="saveLoading" @click="save">
              {{ t('exampleDemo.save') }}
            </BaseButton>
            <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
          </template>
        </Dialog>
      </ContentWrap>
    </div>
  </div>
</template>
<style scoped lang="less">
:deep(.el-col-4, .el-col-4.is-guttered),
:deep(.el-col-5, .el-col-5.is-guttered) {
  padding-right: 30px !important;
  //   position: relative;
  //   position: absolute;
}
:deep(.el-card__header) {
  padding: 15px !important;
}
#detector :deep(.el-card__header) {
  padding-left: 110px !important;
}
:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
